package com.sskj.api.service.impl;

import com.sskj.api.exception.LogicException;
import com.sskj.api.properties.FileProperties;
import com.sskj.api.service.IFileUploadService;
import com.sskj.api.vo.UploadFileResult;
import com.sskj.common.util.FileUtil;
import com.sskj.common.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;

@Service
@Slf4j
public class LocalFileUploadService implements IFileUploadService {

    @Autowired
    private FileProperties fileProperties;

    @Override
    public UploadFileResult upload(MultipartFile multipartFile) {
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        String month = String.format("%02d", localDate.getMonthValue());

        String dir = year + File.separator + month;
        String filename = IdUtil.fastUUID() + "." + FileUtil.extName(multipartFile.getOriginalFilename());
        return upload(multipartFile, dir, filename);
    }

    @Override
    public UploadFileResult upload(MultipartFile multipartFile, String dir, String filename) {
        if (multipartFile.isEmpty() || multipartFile.getSize() <= 0) {
            throw new LogicException("文件不能为空");
        }

        String uploadFileDir = fileProperties.getUploadDir();
        Path path = Paths.get(fileProperties.getUploadDir());
        if (!path.isAbsolute()) {
            uploadFileDir = Paths.get("").toAbsolutePath().resolve(fileProperties.getUploadDir()).normalize().toString();
        }

        String absoluteDirPath = uploadFileDir + File.separator + dir;
        File parentFile = new File(absoluteDirPath);
        if (!parentFile.exists()) {
            if (!parentFile.mkdirs()) {
                log.error("创建目录失败，目录: {}", dir);
                throw new LogicException("文件上传异常");
            }
        }

        String absoluteFilePath = absoluteDirPath + File.separator + filename;
        File file = new File(absoluteFilePath);
        try {
            Files.copy(multipartFile.getInputStream(), file.toPath());
        } catch (IOException e) {
            log.error("文件上传失败，异常信息: {}", e.getMessage());
            throw new LogicException("文件上传异常");
        }

        String filePath = dir + File.separator + filename;
        String fileUrl = fileProperties.getUploadDir() + "/" + filePath.replaceAll("\\\\", "/");
        return new UploadFileResult(fileUrl);
    }
}
